package middleware

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func FixEmptyIDMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 只处理 POST/PUT 且 Content-Type 为 application/json 的请求
		if c.Request.Method != http.MethodPost && c.Request.Method != http.MethodPut {
			c.Next()
			return
		}
		if !strings.Contains(c.GetHeader("Content-Type"), "application/json") {
			c.Next()
			return
		}

		// 读取原始 Body
		bodyBytes, err := ioutil.ReadAll(c.Request.Body)
		if err != nil || len(bodyBytes) == 0 {
			c.Next()
			return
		}

		// 反序列化为 map
		var bodyMap map[string]interface{}
		if err := json.Unmarshal(bodyBytes, &bodyMap); err != nil {
			// 不是合法 JSON 直接跳过
			c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
			c.Next()
			return
		}

		// 替换 id: "" 为 id: 0
		if idVal, ok := bodyMap["id"]; ok {
			if strVal, isString := idVal.(string); isString && strVal == "" {
				bodyMap["id"] = 0
			}
		}

		// 重新序列化并设置回请求体
		newBody, _ := json.Marshal(bodyMap)
		c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))

		c.Next()
	}
}
